 (*********************************************************************
     *                                                                   *
     *  Borland Delphi 4,5,6,7 API for                                   *
     *  Intel Open Source Computer Vision Library                        *
fCvSize2D32f     *                                                                   *
     *                                                                   *
     *  Portions created by Intel Corporation are                        *
     *  Copyright (C) 2000, Intel Corporation, all rights reserved.      *
     *                                                                   *
     *  The original files are: CV.h, CVTypes.h, highgui.h               *
     *                                                                   *
     *                                                                   *
     *  The original Pascal code is: OpenCV.pas,  released 29 May 2003.  *
     *                                                                   *
     *  The initial developer of the Pascal code is Vladimir Vasilyev    *
     *                  home page : http://www.nextnow.com               *
     *                  email     : Vladimir@nextnow.com                 *
     *                              W-develop@mtu-net.ru                 *
     *                                                                   *
     *  Contributors: Andrey Klimov                                      *
     *********************************************************************
     *  Expanded version to use CAMShift functions                       *
     *  G. De Sanctis - 9/2005                                           *
     *                                                                   *
     *********************************************************************
     *                                                                   *
     *                                                                   *
     *  The contents of this file are used with permission, subject to   *
     *  the Mozilla Public License Version 1.1 (the "License"); you may  *
     *  not use this file except in compliance with the License. You may *
     *  obtain a copy of the License at                                  *
     *  http://www.mozilla.org/MPL/MPL-1.1.html                          *
     *                                                                   *
     *  Software distributed under the License is distributed on an      *
     *  "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or   *
     *  implied. See the License for the specific language governing     *
     *  rights and limitations under the License.                        *
     *                                                                   *
     *********************************************************************)


unit UOpenCV;

{$A+,Z+}
{$ASSERTIONS on}

interface

uses
  Windows,Sysutils,Math,Graphics, Types;

const
 HighGUI_DLL='../OpenCV/highgui100.dll';
 cxCore = '../OpenCV/CXCORE100.DLL';
 cvDLL = '../OpenCV/CV100.DLL';
 cvDLL1 = '../OpenCV/CV.DLL';

 IPL_DEPTH_SIGN = $80000000 ;
 CV_PI = PI;
 IPL_DEPTH_1U  =   1    ;
 IPL_DEPTH_8U  =   8   ;
 IPL_DEPTH_16U =  16   ;
 IPL_DEPTH_32F =  32    ;

 CV_VALUE = 1;
 CV_ARRAY = 2;

 IPL_DEPTH_8S = (IPL_DEPTH_SIGN or  8) ;
 IPL_DEPTH_16S= (IPL_DEPTH_SIGN or 16);
 IPL_DEPTH_32S =(IPL_DEPTH_SIGN or 32);

 IPL_DATA_ORDER_PIXEL=  0;
 IPL_DATA_ORDER_PLANE = 1;

 IPL_ORIGIN_TL= 0  ;
 IPL_ORIGIN_BL= 1  ;

 IPL_ALIGN_4BYTES=   4;
 IPL_ALIGN_8BYTES=   8 ;
 IPL_ALIGN_16BYTES= 16 ;
 IPL_ALIGN_32BYTES= 32 ;

 IPL_ALIGN_DWORD =  IPL_ALIGN_4BYTES;
IPL_ALIGN_QWORD  = IPL_ALIGN_8BYTES;

 IPL_BORDER_CONSTANT=   0  ;
 IPL_BORDER_REPLICATE=  1 ;
 IPL_BORDER_REFLECT  =  2 ;
 IPL_BORDER_WRAP    =   3;


 CV_8U =  0;
 CV_8S  = 1;
 CV_16U = 2;
 CV_16S = 3;
 CV_32S = 4;
 CV_32F = 5;
 CV_64F = 6;
 CV_USRTYPE1= 7;

 CV_32FC1 = CV_32F + 0*8;

 CV_MAT_TYPE_MASK = 31;
 CV_MAT_MAGIC_VAL = $42420000;
 CV_MAT_CONT_FLAG_SHIFT = 9;
 CV_MAT_CONT_FLAG = 1 shl CV_MAT_CONT_FLAG_SHIFT;

 CV_MAT_CN_MASK = 3 shl 3;
 CV_MAT_DEPTH_MASK = 7;

 CV_RODRIGUES_M2V = 0;
 CV_RODRIGUES_V2M = 1;
 CV_MAGIC_MASK    = $FFFF0000 ;

 CV_LU  = 0;
 CV_SVD = 1;

 CV_BGR2Gray  = 6;

  CV_GRAY2BGR   = 8;
  CV_GRAY2RGB   = CV_GRAY2BGR ;
  CV_GRAY2BGRA  = 9;
  CV_GRAY2RGBA  = CV_GRAY2BGRA;
  CV_BGRA2GRAY  = 10;
 CV_RGBA2GRAY  = 11;

 CV_RGB2GRAY = 7;
 CV_BGR2HSV = 40;
 CV_FILLED = -(1);
 CV_AA = 16;

  CV_LKFLOW_PYR_A_READY =      1;
  CV_LKFLOW_PYR_B_READY =      2;
  CV_LKFLOW_INITIAL_GUESSES =  4;
  CV_POLY_APPROX_DP = 0;

  CV_SHAPE_RECT         =   0;
  CV_SHAPE_CROSS        =   1;
  CV_SHAPE_ELLIPSE      =   2;
  CV_SHAPE_CUSTOM       =   100;

  CV_WINDOW_AUTOSIZE    =   1;

  CV_CMP_EQ             =   0;
  CV_GAUSSIAN_5x5       =   7;
const
// basic font types
 CV_FONT_HERSHEY_SIMPLEX      =   0   ;
 CV_FONT_HERSHEY_PLAIN  =         1  ;
 CV_FONT_HERSHEY_DUPLEX  =        2  ;
 CV_FONT_HERSHEY_COMPLEX  =       3 ;
 CV_FONT_HERSHEY_TRIPLEX   =      4 ;
 CV_FONT_HERSHEY_COMPLEX_SMALL =  5  ;
 CV_FONT_HERSHEY_SCRIPT_SIMPLEX = 6  ;
 CV_FONT_HERSHEY_SCRIPT_COMPLEX = 7 ;

// font flags
 CV_FONT_ITALIC  =               16  ;
CV_FONT_VECTOR0  =  CV_FONT_HERSHEY_SIMPLEX;




//* Font structure
type
//PCvFont = ^CvFont
CvFont = record
    font_face : integer; //* =CV_FONT_* */
    ascii : pInteger; //* font data and metrics
    greek ,cyrillic: pInteger;
    hscale, vscale ,
    shear: float;//* slope coefficient: 0 - normal, >0 - italic */
    thickness : integer; //
    dx : float; //* horizontal interval between letters */
    line_type : integer;
end;
  pCVFont = ^CvFont;
{
     pCvPoint = ^CvPoint;
     CvPoint = record
          x : longint ;
          y : longint;
       end;
}
type
CvSlice = record
    start_index :integer;
    end_index   :integer;
end;

const
//inline CvSlice cvSlice( int start, int end );
// cvSlice_ = fo (event, x, y, flags  : integer ; param : pointer) ;
CV_WHOLE_SEQ_END_INDEX =$3fffffff;
//CV_WHOLE_SEQ  =cvSlice_(0, CV_WHOLE_SEQ_END_INDEX);

type
  CvContourRetrievalMode = ( CV_RETR_EXTERNAL , //retrieves only the extreme outer contours (list);
                      CV_RETR_LIST, // retrieves all the contours (list);
                      CV_RETR_CCOMP, // retrieves the two-level hierarchy (list of connected components);
                      CV_RETR_TREE ); // retrieves the complete hierarchy (tree).

  CvChainApproxMethod = (CV_CHAIN_CODE,CV_CHAIN_APPROX_NONE,CV_CHAIN_APPROX_SIMPLE,CV_CHAIN_APPROX_TC89_L1,CV_CHAIN_APPROX_TC89_KCOS,CV_LINK_RUNS);
  PCvVect32f = PSingle;
  TCvVect32fArr=array of Single;

  PCvMatr32f = PSingle;
  TCvMatr32fArr=array of Single;

  TIntegerArr=array of Integer;


  CvSize = record
            width  : integer;
            height : integer;
           end;
  TCvSize = CvSize;
  PCvSize = ^TCvSize;


  CvPoint2D32f = record
                    x : Single;
                    y : Single;
                 end;
  TCvPoint2D32f = CvPoint2D32f;
  PCvPoint2D32f = ^TCvPoint2D32f;
  TCvPoint2D32fArr=array of TCvPoint2D32f;


  CvPoint3D32f = record
                    x : Single;
                    y : Single;
                    z : Single;
                 end;
  TCvPoint3D32f = CvPoint3D32f;
  PCvPoint3D32f = ^TCvPoint3D32f;
  TCvPoint3D32fArr=array of TCvPoint3D32f;

  TMatData = record
              ptr: PUCHAR;
              s : PSmallInt ;
              i : pInteger;
              fl : pFloat;
              db : pDouble;
             end;

  CvMat = record
            type_    : Integer;
            step     : Integer;
            refcount : PInteger;
            hdr_refcount : integer;
            rows ,width    : Integer;
            cols ,height     : Integer;
              ptr: PUCHAR;
              s : PSmallInt ;
              i : pInteger;
              fl : pFloat;
              db : pDouble;

          end;

  TCvMat = CvMat;
  PCvMat = ^TCvMat;

    { CvArr* is used to pass arbitrary array-like data structures      into the functions where the particular
      array type is recognized at runtime  }
  PCvArr = Pointer;
  P2PCvArr = ^PCvArr;

//****************************************************************************************/
//*                       Multi-dimensional dense array (CvMatND)                          *
//****************************************************************************************/
  const
     CV_MATND_MAGIC_VAL = $42430000;
     CV_TYPE_NAME_MATND = 'opencv-nd-matrix';
     CV_MAX_DIM = 32;
     CV_MAX_DIM_HEAP = 1 shl 16;

  type

     CvMatND = record
          _type : longint;
          dims : longint;
          refcount : ^longint;
          data : record
              case longint of
                 0 : ( ptr : ^uchar );
                 1 : ( fl : ^double );
                 2 : ( db : ^double );
                 3 : ( i : ^longint );
                 4 : ( s : ^smallint );
              end;
          dim : array[0..(CV_MAX_DIM)-1] of record
               size : longint;
               step : longint;
            end;
       end;

  {***************************************************************************************/
  *                                         Histogram                                      *
  /*************************************************************************************** }

  type

     CvHistType = longint;

  const
     CV_HIST_MAGIC_VAL = $42450000;
     CV_HIST_UNIFORM_FLAG = 1 shl 10;
  { indicates whether bin ranges are set already or not  }
     CV_HIST_RANGES_FLAG = 1 shl 11;
     CV_HIST_ARRAY = 0;
     CV_HIST_SPARSE = 1;
     CV_HIST_TREE = CV_HIST_SPARSE;
  { should be used as a parameter only,
     it turns to CV_HIST_UNIFORM_FLAG of hist->type  }
     CV_HIST_UNIFORM = 1;
  { for uniform histograms  }
  { for non-uniform histograms  }
  { embedded matrix header for array histograms  }
  type
     CvHistogram = record
          _type : longint;
          bins : PCvArr;
          thresh : array[0..(CV_MAX_DIM)-1] of array[0..1] of float;
          thresh2 : P2Pfloat;
          mat : CvMatND;
       end;
   PCvHistogram = ^CvHistogram;

//******************************** Memory storage ****************************************/
Type
  PCvMemBlock = ^TCvMemBlock;
  CvMemBlock = Record
                 prev : PCvMemBlock;
                 next : PCvMemBlock;
               end;
  TCvMemBlock = CvMemBlock;

Const CV_STORAGE_MAGIC_VAL = $42890000;

Type
  PCvMemStorage = ^TCvMemStorage;
  CvMemStorage = Record
                   signature : integer;
                   bottom    : PCvMemBlock;   //* first allocated block */
                   top       : PCvMemBlock;   //* current memory block - top of the stack */
                   parent    : PCvMemStorage; //* borrows new blocks from */
                   block_size: integer;       //* block size */
                   free_space: integer;       //* free space in the current block */
                 end;
  TCvMemStorage = CvMemStorage;


   {********************************** Sequence ****************************************** }
  { previous sequence block  }
  { next sequence block  }
  { index of the first element in the block +
                                   sequence->first->start_index  }
  { number of elements in the block  }
  { pointer to the first element of the block  }

  type

     PCvSeqBlock = ^CvSeqBlock;
     CvSeqBlock = record
          prev : PCvSeqBlock;
          next : PCvSeqBlock;
          start_index : longint;
          count : longint;
          data : Pchar;
       end;

   PCvSeq = ^CvSeq;
   PCvSeqArr = ^TCvSeqArr;
   TCvSeqArr = array[0..65535] of CvSeqBlock;

   pcvTreeNodeType = ^cvTreeNodeType;
   cvTreeNodeType = record
      flags : integer;         //* micsellaneous flags */          /
      header_size : integer;   //* size of sequence header */      /
      h_prev: pcvTreeNodeType; //* previous sequence */        /
      h_next: pcvTreeNodeType; //* next sequence */            /
      v_prev: pcvTreeNodeType; //* 2nd previous sequence */    /
      v_next: pcvTreeNodeType;
    end;   // 2nd next sequence */
     pCvRect = ^cvRect;
     CvRect = record
          x : integer;
          y : integer;
          width : integer;
          height : integer;
       end;

     CvSeq = record
          flags : longint;
          header_size : longint;
          h_prev : PCvSeq;
          h_next : PCvSeq;
          v_prev : PCvSeq;
          v_next : PCvSeq;
          total : longint;
          elem_size : longint;
          block_max : Pchar;
          ptr : Pchar;
          delta_elems : longint;
          storage : PCvMemStorage;
          free_blocks : PCvSeqBlock;
          first : PCvSeqBlock;
       end;

{************************************ CvScalar **************************************** }

     CvScalar = record
          val : array[0..3] of double;
       end;


{************************************** CvRect **************************************** }
    PCvContour = ^CvContour;
    CvContour = record
    //---- Seq
      flags : integer;
      header_size : integer;
      h_prev : PCvContour;
      h_next : PCvContour;
      v_prev : PCvContour;
      v_next : PCvContour;
      // CV_SEQUENCE_FIELDS
      total : longint;
      elem_size : longint;
      block_max : Pchar;
      ptr : Pchar;
      delta_elems : longint;
      storage : PCvMemStorage;
      free_blocks : PCvSeqBlock;
      first : PCvSeqBlock;
      //CV_SEQUENCE_FIELDS
      rect : CvRect ;
      color : integer;
      reserved : array [0..2] of integer;
    end;
  type

  {*************************** Connected Component  ************************************* }
  { area of the connected component   }
  { average color of the connected component  }
  { ROI of the component   }
  { optional component boundary
           (the contour might have child contours corresponding to the holes) }

     CvConnectedComp = record
          area : double;
          value : CvScalar;
          rect : CvRect;
          contour : PCvSeq;
       end;
     PCvConnectedComp = ^CvConnectedComp;
{****************************** CvPoint and variants ********************************** }
  type
     PIntegerArray = ^TIntegerArray;
     TIntegerArray = array[0..65535] of Integer;

     pCvPoint = ^CvPoint;
     CvPoint = record
          x : longint ;
          y : longint;
       end;
     pCvPointArray = ^TCvPointArray;
     TCvPointArray = array[0..65535] of CvPoint;

  const

  CVPOINT0 : CvPoint =
      (
        x : 0;
        y : 0;      ) ;

  type
     CvPoint2D64f = record
          x : double;
          y : double;
       end;

     CvPoint3D64f = record
          x : double;
          y : double;
          z : double;
       end;

     CvSize2D32f = record
          width : float;
          height : float;
       end;
  { center of the box  }
  { box width and length  }
  { angle between the horizontal axis
                               and the first side (i.e. length) in radians  }

     CvBox2D = record
          center : CvPoint2D32f;
          size : CvSize2D32f;
          angle : float;
       end;
     PCvBox2D = ^CvBox2D;
  { Line iterator state  }
  { pointer to the current point  }
  { Bresenham algorithm state  }

     CvLineIterator = record
          ptr : ^uchar;
          err : longint;
          plus_delta : longint;
          minus_delta : longint;
          plus_step : longint;
          minus_step : longint;
       end;


//*********************************** CvTermCriteria *************************************/
Const
 CV_TERMCRIT_ITER = 1;
 CV_TERMCRIT_NUMB = CV_TERMCRIT_ITER;
 CV_TERMCRIT_EPS  = 2;

Type
  CvTrackbarCallback = procedure(pos : integer);
  CvMouseCallback = procedure (event, x, y, flags  : integer ; param : pointer) ;

  CvTermCriteria  = Record
                      type_   : integer;  { may be combination of CV_TERMCRIT_ITER, CV_TERMCRIT_EPS }
                      maxIter : integer;
                      epsilon : double;
                    end;
  TCvTermCriteria = CvTermCriteria;


{/*********************************** CvTermCriteria *************************************}

{CVAPI(int) cvCreateTrackbar( const char* trackbar_name, const char* window_name,
                             int* value, int count, CvTrackbarCallback on_change );}
 function   cvCreateTrackbar( trackbar_name : pChar; window_name : pChar;
                              value : pinteger; count : integer; on_change :CvTrackbarCallback) : integer;cdecl;


 procedure  cvCircle( img: PCvArr; center: CvPoint; radius: longint;
                       color: CvScalar; thickness: longint = 1;
                       line_type: longint = 8; shift: longint = 0); cdecl;


{ assign callback for mouse events */
 HIGHGUI CVAPI(void) cvSetMouseCallback( const char* window_name, CvMouseCallback on_mouse,
                                void* param CV_DEFAULT(NULL)); }
 procedure  cvSetMouseCallback(window_name :pchar; onMouse : cvMouseCallBack; param : pointer = nil);cdecl;

 Procedure cvFindExtrinsicCameraParams( numPoints         : integer;
                                        imageSize         : TCvSize;
                                        imagePoints32f    : PCvPoint2D32f;
                                        objectPoints32f   : PCvPoint3D32f;
                                        focalLength32f    : PCvVect32f;
                                        principalPoint32f : TCvPoint2D32f;
                                        distortion32f     : PCvVect32f;
                                        rotVect32f        : PCvVect32f;
                                        transVect32f      : PCvVect32f
                                        ); cdecl;


{ Calibrates camera using multiple views of calibration pattern }
{
 Procedure  cvCalibrateCamera2( numImages         : Integer;        //int
                               numPoints         : PInteger;       //int*
                               imageSize         : TCvSize;        //CvSize
                               imagePoints32f    : PCvPoint2D32f;  //CvPoint2D32f*
                               objectPoints32f   : PCvPoint3D32f;  //CvPoint3D32f*
                               distortion32f     : PCvVect32f;     //CvVect32f
                               cameraMatrix32f   : PCvMatr32f;     //CvMatr32f
                               transVects32f     : PCvVect32f;     //CvVect32f
                               rotMatrs32f       : PCvMatr32f;     //CvMatr32f
                               useIntrinsicGuess : Integer         //int
                               ); cdecl;
    }

 procedure  cvLine( img : pCvArr;  pt1, pt2 : CvPoint;
                    color : CvScalar; thickness:integer;line_type : integer = 8; shift :integer = 0);cdecl;

 { CVAPI(CvMat*)  cvCreateMatHeader( int rows, int cols, int type ); }
 function  cvCreateMatHeader( rows, cols, atype : integer ) : pCvMat; cdecl;

 Procedure cvRodrigues( rotMatrix : PCVMAT;
                        rotVector : PCVMAT;
                        jacobian  : PCVMAT;
                        convType  : Integer ); cdecl ;



 { Allocates array data }
 Procedure cvCreateData(var arr : PCvArr ); cdecl;
 { Releases array data  }
 Procedure cvReleaseData(arr : Pointer ); cdecl;

{ /* Allocates and initalizes CvMat header */
CVAPI(CvMat*)  cvCreateMat( int rows, int cols, int type );}
 function  cvCreateMat(rows,cols,atype : integer ) : pCvMat ;cdecl;

const  CV_INTER_NN  =      0;
  CV_INTER_LINEAR =   1;
  CV_INTER_CUBIC  =   2;
  CV_INTER_AREA   =   3;
  CV_WARP_FILL_OUTLIERS =8;
 CV_WARP_INVERSE_MAP  =16 ;



{ Computes rotation_matrix matrix
  CVAPI(CvMat*)  cv2DRotationMatrix( CvPoint2D32f center, double angle,    double scale, CvMat* map_matrix ); }
 function  cv2DRotationMatrix(center :CvPoint2D32f ; angle,scale : double; map_matrix : pCvMat ) : pCvMat ;cdecl;
{ CVAPI(void)  cvWarpAffine( const CvArr* src, CvArr* dst, const CvMat* map_matrix,
                           int flags CV_DEFAULT(CV_INTER_LINEAR+CV_WARP_FILL_OUTLIERS),
                           CvScalar fillval CV_DEFAULT(cvScalarAll(0)) ); }
 procedure cvWarpAffine(src,dst : pcvArr; map_matrix : pCvMat; flags : integer ; fillval : cvScalar );cdecl;

 Function  cvInvert( const A : PCvArr; B : PCvArr; method : integer ) : double; cdecl;
 Function  cvPseudoInverse( const src : PCvArr; dst : PCvArr ) : double;

 Procedure cvMatMulAdd( const  A,B,C : PCvArr;  D : PCvArr ); cdecl;
 Procedure cvMatMul( A,B,D : PCvArr );


 Function  cvMat_( rows, cols, type_: Integer; data : Pointer ):TCvMat;
 Function  cvmGet( const mat : PCvMat; i, j : integer): Single;
 Procedure cvmSet( mat : PCvMat; i, j : integer; val: Single);

 Function  cvSize_( width, height : integer ) : TcvSize;
{
 Function cvFont_( font_face : integer;ascii,greek ,cyrillic:pInteger;
 hscale, vscale , shear: float; thickness : integer; dx : float; line_type : integer) : TCvFont;
 }
 { load image from file
   iscolor: >0 - output image is always color,
             0 - output image is always grayscale,
            <0 - output image is color or grayscale dependending on the file }
 Function  cvLoadImage( const filename : PChar; iscolor : integer=1) : PIplImage; cdecl;
 Function  cvSaveImage( const filename : PChar; const image : Pointer) : integer; cdecl;

   { Finds a sparse set of points within the selected region
   that seem to be easy to track }
 procedure  cvGoodFeaturesToTrack( image: PCvArr;
                                   eig_image: PCvArr;
                                   temp_image: PCvArr;
                                   corners: PCvPoint2D32f;
                                   corner_count: PINT;
                                   quality_level: Double;
                                   min_distance: double;
                                   mask: PCvArr = nil;
                                   block_size: longint = 3;
                                   use_harris: longint = 0;
                                   k: double = 0.04 ); cdecl;

{ It is Lucas & Kanade method, modified to use pyramids.
   Also it does several iterations to get optical flow for
   every point at every pyramid level.
   Calculates optical flow between two images for certain set of points (i.e.
   it is a "sparse" optical flow, which is opposite to the previous 3 methods) }
 procedure  cvCalcOpticalFlowPyrLK( prev: PCvArr;
                                    curr: PCvArr;
                                     prev_pyr: PCvArr;
                                     curr_pyr: PCvArr;
                                     prev_features: PCvPoint2D32f;
                                     curr_features: PCvPoint2D32f;
                                     count: longint;
                                     win_size: CvSize;
                                     level: longint;
                                     status: pchar;
                                     track_error: PSingle;
                                     criteria: CvTermCriteria;
                                     flags: longint );  cdecl;


 {CVAPI(char*)  cvGetSeqElem( const CvSeq* seq, int index ); }
 function   cvGetSeqElem(const seq  : pCvSeq ; index : integer):pchar;cdecl;
 { Allocates and initializes IplImage header }
 Function cvCreateImageHeader( size : TCvSize; depth, channels : integer ) : PIplImage; cdecl;
 { Releases (i.e. deallocates) IPL image header  : void  cvReleaseImageHeader( IplImage** image );}
 Procedure cvReleaseImageHeader( var image : PIplImage ); cdecl;
 { Releases IPL image header and data }
 procedure cvReleaseImage(var image: PIplImage); cdecl;
 { Creates a copy of IPL image (widthStep may differ). }
 Function  cvCloneImage( const image : PIplImage ) : PIplImage; cdecl;

 function cvCreateStructuringElementEx( cols,rows,anchor_x,anchor_y,shape : integer;values_ :Pinteger=nil ) : pIplConvKernel; cdecl;
 //Function cvCreateStructuringElementEx( cols,rows,anchor_x,anchor_y,shape : integer;values :Pinteger=nil ) : PIplImage; cdecl;
 function cvCreateSeq(seq_flags,header_size,elem_size: integer ; storage :pCvMemStorage ) : pCvSeq; cdecl;
 procedure cvErode(src,dst:PIplImage ; b:pIplConvKernel=nil;iterations :integer=1)  ; cdecl;
 procedure cvDilate(src,dst:PIplImage ; b:pIplConvKernel=nil;iterations :integer=1)  ; cdecl;
 procedure cvPyrUp(src,dst:PIplImage ; filter:TIplFilter )  ; cdecl;

 procedure cvInitFont(Font:pCvFont; Font_face:integer; Hscale,vscale:double; shear:double=0;thickness:integer=1; line_type:integer=8)  ; cdecl;
 procedure cvPutText(src:PIplImage ;const text:Pchar;Origin:CvPoint;const font:pCvFont;color:CvScalar)  ; cdecl;
// function  cvContourArea (const contour:Pcvarr;slice:CvSlice=CV_WHOLE_SEQ ) : double; cdecl;


const  CV_HOUGH_STANDARD =0 ;
       CV_HOUGH_PROBABILISTIC = 1 ;
       CV_HOUGH_MULTI_SCALE = 2   ;
       CV_HOUGH_GRADIENT =3;

 { Converts input array from one color space to another. }
 Procedure cvCvtColor( const src : Pointer; dst : Pointer; colorCvtCode : integer );  cdecl;

{ CVAPI(void)  cvThreshold( const CvArr*  src, CvArr*  dst,
                          double  threshold, double  max_value,                           int threshold_type );}

// Types of thresholding
const
 CV_THRESH_BINARY   =   0;  // value = value > threshold ? max_value : 0       */
 CV_THRESH_BINARY_INV = 1;  // value = value > threshold ? 0 : max_value       */
 CV_THRESH_TRUNC   =    2 ; // value = value > threshold ? threshold : value   */
 CV_THRESH_TOZERO  =    3 ; // value = value > threshold ? value : 0           */
 CV_THRESH_TOZERO_INV=  4 ; // value = value > threshold ? 0 : value           */
 CV_THRESH_MASK     =   7 ;
 CV_THRESH_OTSU     =   8 ; // use Otsu algorithm to choose the optimal threshold value;                                 combine the flag with one of the above CV_THRESH_* values */

 CV_BLUR_NO_SCALE =0;
 CV_BLUR  =1;
 CV_GAUSSIAN=  2;
 CV_MEDIAN =3 ;
 CV_BILATERAL= 4;
{/* Smoothes array (removes noise)
CVAPI(void) cvSmooth( const CvArr* src, CvArr* dst,
                      int smoothtype CV_DEFAULT(CV_GAUSSIAN),                      int param1 CV_DEFAULT(3),
                      int param2 CV_DEFAULT(0),                      double param3 CV_DEFAULT(0),
                      double param4 CV_DEFAULT(0));}

 procedure cvSmooth( const  src,  dst : pcvArr;  smoothtype :integer = CV_GAUSSIAN ;
                      param1 :integer =3; param2 : integer = 0; param3 : double = 0; param4 : double = 0); cdecl;

  procedure cvThreshold( src : pCvArr;   dst : pCvArr ;  threshold,max_value : double; threshold_type  :integer );cdecl;

 { CVAPI(void)  cvCanny( const CvArr* image, CvArr* edges, double threshold1,
                      double threshold2, int  aperture_size CV_DEFAULT(3) ); }
  procedure cvCanny( image : pCvArr;   edges : pCvArr ;  threshold1,threshold2 : double; aperture_Size  :integer = 3);cdecl;

{CVAPI(CvSeq*)  cvHoughLines2( CvArr* image, void* line_storage, int method,
                              double rho, double theta, int threshold,     double param1 CV_DEFAULT(0), double param2 CV_DEFAULT(0));}
  function cvHoughLines2( image : pCvArr;   line_storage : pointer ;  method : integer; rho, theta : double; threshold : integer ;
                           param1 : double = 0; param2 : double =0 ) : PCvSeq;cdecl;

{  CVAPI(void) cvSobel( const CvArr* src, CvArr* dst,
                    int xorder, int yorder,                    int aperture_size CV_DEFAULT(3));}

  procedure cvSobel(const image : PIplImage;   edges : PIplImage ; xOrder, yOrder : longint; aperture_Size  :integer = 3);cdecl;
{ CVAPI(void) cvLaplace( const CvArr* src, CvArr* dst,                      int aperture_size CV_DEFAULT(3) );}
  procedure cvLaplace(const image : PIplImage;   dst : PIplImage ; aperture_Size  :integer = 3);cdecl;

 { Creates new memory storage.
   block_size == 0 means that default, somewhat optimal size, is used (currently, it is 64K). }

 Function  cvCreateMemStorage( block_size : integer ) : PCvMemStorage; cdecl;
 { Releases memory storage. All the children of a parent must be released before
   the parent. A child storage returns all the blocks to parent when it is released  }
 Procedure cvReleaseMemStorage( var storage : PCvMemStorage ); cdecl;
 Procedure cvClearMemStorage( storage : PCvMemStorage ); cdecl;

{
   int cvFindContours(IplImage* img, CvMemStorage* storage, CvSeq** firstContour, int headerSize=sizeof(CvContour),
                      CvContourRetrievalMode mode=CV_RETR_LIST,CvChainApproxMethod
                      method=CV_CHAIN_APPROX_SIMPLE);
 }

 { Detects corners on a chess-board - "brand" OpenCV calibration pattern }
 Function  cvFindChessBoardCornerGuesses( const arr          : Pointer;
                                                thresh       : Pointer;
                                                storage      : PCvMemStorage;
                                                etalon_size  : TCvSize;
                                                corners      : PCvPoint2D32f;
                                                corner_count : PInteger ) : integer;  cdecl;

 {  Adjust corner position using some sort of gradient search }
 Procedure  cvFindCornerSubPix( const src         : Pointer;
                                      corners     : PCvPoint2D32f;
                                      count       : integer;
                                      win         : TCvSize;
                                      zero_zone   : TCvSize;
                                      criteria    : TCvTermCriteria ); cdecl;

 {-----------------------------------------------}

//*********************** Haar-like Object Detection structures **************************
const
 CV_HAAR_MAGIC_VAL =   $42500000;
 CV_TYPE_NAME_HAAR  = 'opencv-haar-classifier';
 CV_HAAR_FEATURE_MAX = 10;
{#define CV_IS_HAAR_CLASSIFIER( haar )                                                    /
    ((haar) != NULL &&                                                                   /
    (((const CvHaarClassifierCascade*)(haar))->flags & CV_MAGIC_MASK)==CV_HAAR_MAGIC_VAL)
           }
type

CvHaarFeatureData = record
  r : cvRect;
  weight : float;
end;
pCvHaarFeature = ^CvHaarFeature;
CvHaarFeature = record
    tilted : integer;
    rect : array [0..CV_HAAR_FEATURE_MAX-1] of CvHaarFeatureData;
end;
pCvHaarClassifier = ^CvHaarClassifier;
CvHaarClassifier = record
    count : integer;
    haar_feature : pCvHaarFeature;
    threshold : pFloat;
    left : pInteger;
    right : pInteger;
    alpha : pFloat;
end;

CvHaarStageClassifier = record
     count : integer;
     threshold : float;
     classifier :  pCvHaarClassifier;
     next, child, parent : integer;
end;

CvHidHaarClassifierCascade = record end;

pCvHaarStageClassifier  = ^CvHaarStageClassifier;
pCvHaarClassifierCascade = ^CvHaarClassifierCascade ;

CvHaarClassifierCascade = record
    flags ,count : integer;
    orig_window_size : CvSize;
    real_window_size : CvSize;
    scale:double;
    stage_classifier: pCvHaarStageClassifier;
    hid_cascade:CvHidHaarClassifierCascade;
end;

CvAvgComp = record
    rect : cvRect;
    neighbors : integer;
end;

pCvAttrList = ^CvAttrList;
CvAttrList = record
    attr : pChar; //* NULL-terminated array of (attribute_name,attribute_value) pairs */
    next : pCvAttrList; //* pointer to next chunk of the attributes list */
end;

const
  CV_HAAR_DO_CANNY_PRUNING = 1;

 function CV_IS_HAAR_CLASSIFIER(haar : pointer) : boolean;
{CVAPI(CvSeq*) cvHaarDetectObjects( const CvArr* image,
                     CvHaarClassifierCascade* cascade,
                     CvMemStorage* storage, double scale_factor CV_DEFAULT(1.1),
                     int min_neighbors CV_DEFAULT(3), int flags CV_DEFAULT(0),
                     CvSize min_size CV_DEFAULT(cvSize(0,0))); }
  function  cvHaarDetectObjects(image : pcvArr; cascade :pCvHaarClassifierCascade; storage : pcvMemStorage;
                                 scale_factor : double ; min_neighbors : integer ; flags : integer ;
                                  min_size : cvSize  ) : pcvSeq; cdecl;

//* simple API for reading/writing data */
 procedure cvSave(fileName : pChar;struct_ptr : pointer; name : pChar ; comment :pChar ; attributes :  pCvAttrList);cdecl;

  function cvLoad(fileName : pChar; memstorage : pCvMemStorage =nil; name : pChar =nil; real_name :ppChar =nil ) : pointer ; cdecl;
{-----------------------------------------------------------------------}
  {Delphi procedure to convert a OCV iplImage to a Delphi bitmap}
  procedure IplImage2Bitmap(iplImg: PIplImage; var bitmap: TBitmap);


  {functions/procedures not in DLL, written in this unit}
  function cvScalar_(val0:double; val1:double; val2:double; val3:double):CvScalar;
  function cvScalarAll_(val0123:double):CvScalar;
  function cvFloor(value: double): longint;
  function cvRound(value:double):longint;
  function cvPoint_( x, y: longint ): CvPoint;
//  function cvSlice_( x, y: integer ): Integer;
  function cvPoint2D32f_(  x, y: single  ): cvPoint2D32f;
  function cvPointFrom32f_( point: CvPoint2D32f ): CvPoint;
  function cvTermCriteria_( type_: longint; max_iter: longint; epsilon: double ): CvTermCriteria;
  function CV_RGB(r,g,b : longint) : CvScalar;
  procedure cvEllipseBox(img:PCvArr; box:CvBox2D; color:CvScalar; thickness:longint;
              line_type:longint; shift:longint);
  function  cvRect_( x, y, width, height: longint ): CvRect;

  procedure CV_SWAP(var a, b, t: pointer);

  function hsv2rgb(  hue : float )  :CvScalar ;
  function  cvPointTo32f_(point: CvPoint ):  CvPoint2D32f;

  procedure cvCalcBackProject(image:P2PIplImage; dst:PCvArr; hist:PCvHistogram);
  procedure cvCalcHist(image:P2PIplImage; hist:PCvHistogram; accumulate:longint; mask:PCvArr);

 {-----------------------------------------------}

 function cvFindContours( img : PIplImage; storage : PCvMemStorage;
                          firstContour : PCvSeq; headerSize :integer;
                          mode : CvContourRetrievalMode ;
                          method :CvChainApproxMethod  ;
                          offset : CvPoint ) : integer ; cdecl;
{ CvSeq* cvApproxPoly( CvSeq* srcSeq, int headerSize, CvMemStorage* storage,
    CvPolyApproxMethod method, float parameter,int recursive=0 ); }
 function cvApproxPoly(  srcSeq : PCvSeq; headerSize :integer;
                          storage : pCvMemStorage ;
                          method :integer  ;
                          parameter : float ;
                          recursive : integer = 0 ) : PCvSeq ; cdecl;

 function cvBoundingRect(  contour : PCvArr;header : integer = 0 ) : cvRect  ; cdecl;

 procedure cvBoxPoints(  box : CvBox2D ; pt : array of  CvPoint2D32f  ) ; cdecl;

{CVAPI(void)  cvSnakeImage( const IplImage* image, CvPoint* points,
                           int  length, float* alpha,
                           float* beta, float* gamma,
                           int coeff_usage, CvSize  win,
                           CvTermCriteria criteria, int calc_gradient CV_DEFAULT(1)); }
 procedure cvSnakeImage ( image : pIplImage; points : pCvPoint; length : integer;
                          alpha : PFloat; beta : pFloat; gamma : pFloat; coeff_Usage : integer;
                          win : CvSize ; criteria  : CvTermCriteria; calc_gradient : integer = 1);cdecl;

 function cvMinAreaRect2(contour : pCvSeq; storage : PCvMemStorage  ) : CvBox2D  ; cdecl;

 procedure cvDrawContours( img : PIplImage; contour : pCvSeq;
                          external_color,hole_color :CvScalar;  v1,v2,v3 : integer ;
                           offset : CvPoint   )  ; cdecl;

  function cvNamedWindow(caption : pchar ; flags : integer) : integer;cdecl;
  procedure cvShowImage(caption : pchar ; img : PIplImage);cdecl;
  procedure cvDestroyWindow(caption : pchar );cdecl;

  function cvWaitKey(delay : integer) : integer;cdecl;
  { Creates IPL image (header and data)  }
  function cvCreateImage(size:CvSize; depth:longint; channels:longint):PIplImage;
                        cdecl;

  { Returns width and height of array in elements  }
  function cvGetSize(const arr: PCvArr):CvSize; cdecl;

  function cvGetSubRect(const arr: PCvArr;submat:PCvArr;rect:CvRect):CvSize; cdecl;

  {IplImage* cvGetImage( const CvArr* arr, IplImage* image_header );       }
  function cvGetImage(const arr: PCvArr;Image_header:PIplImage  ):PIplImage; cdecl;

  procedure cvCmpS(const src:PCvArr;value:double; dst:PCvArr; cmp_op:integer); cdecl;
  { Copies source array to destination array  }
  procedure cvCopy(src:PCvArr; dst:PCvArr; mask:PCvArr); cdecl;

  { dst(idx) = lower <= src(idx) < upper  }
  procedure cvInRangeS(src:PCvArr; lower:CvScalar; upper:CvScalar; dst:PCvArr);
                cdecl;


  { Creates new histogram  }

  function cvCreateHist(dims:longint; sizes:Plongint; _type:longint; ranges:P2Pfloat;
        uniform:longint): PCvHistogram; cdecl;

  { Calculates array histogram  }
  procedure cvCalcArrHist(arr:P2PCvArr; hist:PCvHistogram; accumulate:longint; mask:PCvArr);
                cdecl;

  { Finds indices and values of minimum and maximum histogram bins  }
  procedure cvGetMinMaxHistValue(hist:PCvHistogram; min_value:Pdouble;
                max_value:Pdouble; min_idx:Plongint; max_idx:Plongint);  cdecl;

  { Calculates back project  }
  procedure cvCalcArrBackProject(image:P2PCvArr; dst:PCvArr; hist:PCvHistogram);
                cdecl;


    { Clears all the array elements (sets them to 0)  }

  procedure cvSetZero(arr:PCvArr); cdecl;
  procedure cvZero(arr:PCvArr); cdecl;

  { Sets image ROI (region of interest) (COI is not changed)  }

  procedure cvSetImageROI(image:PIplImage; rect:CvRect); cdecl;

  { Resets image ROI and COI  }
  procedure cvResetImageROI(image:PIplImage); cdecl;

  procedure cvAddWeighted(const src1:PCvarr;alpha:double;const src2:PCvarr;beta:double;gamma:double;dst:PcvArr); cdecl;
  procedure cvAddS(const src1:PCvarr ; value:CvScalar; dst:PcvArr;const mask:PCvArr=nil); cdecl;

  { Performs linear transformation on every source array element:
     dst(x,y,c) = scale*src(x,y,c)+shift.
     Arbitrary combination of input and output array depths are allowed
     (number of channels must be the same), thus the function can be used
     for type conversion  }
  procedure cvConvertScale(src:PCvArr; dst:PCvArr; scale:double; shift:double);            cdecl;

  { Splits a multi-channel array into the set of single-channel arrays or
     extracts particular [color] plane  }

  procedure cvSplit(src:PCvArr; dst0:PCvArr; dst1:PCvArr; dst2:PCvArr; dst3:PCvArr);
                cdecl;

  { dst(idx) = src1(idx) & src2(idx)  }
  procedure cvSubRS(src:PCvArr;value : cvScalar;  dst:PCvArr; mask:PCvArr);  cdecl;
  procedure cvAnd(src1:PCvArr; src2:PCvArr; dst:PCvArr; mask:PCvArr);  cdecl;
  procedure cvSub(src1:PCvArr; src2:PCvArr; dst:PCvArr; mask:PCvArr);  cdecl;
  procedure cvSubS(src:PCvArr; value:cvScalar; dst:PCvArr; mask:PCvArr=nil);  cdecl;
  procedure cvXor(src1:PCvArr; src2:PCvArr; dst:PCvArr; mask:PCvArr = nil);  cdecl;

// Mirror array data around horizontal (flip=0),   vertical (flip=1) or both(flip=-1) axises:
//   cvFlip(src) flips images vertically and sequences horizontally (inplace) */
//CVAPI(void)  cvFlip( const CvArr* src, CvArr* dst CV_DEFAULT(NULL),                      int flip_mode CV_DEFAULT(0));
  procedure cvFlip(src,dest : pcvArr; flip_mode : integer = 0);cdecl;

    { for 1-channel arrays  }
  function cvGetReal1D(arr:PCvArr; idx0:longint):double; cdecl;
  function cvGetReal2D(arr:PCvArr; idx0:longint; idx1:longint):double; cdecl;
  function cvGetReal3D(arr:PCvArr; idx0:longint; idx1:longint; idx2:longint):double; cdecl;
  function cvGetRealND(arr:PCvArr; idx:Plongint):double; cdecl;

  procedure cvSet1D(arr:PCvArr; idx0:longint; aVal:CvScalar); cdecl;
  procedure cvSet2D(arr:PCvArr; idx0,idx1:longint; aVal:CvScalar); cdecl;

  procedure cvSetReal1D(arr:PCvArr; idx0:longint; aVal:double); cdecl;
  procedure cvSetReal2D(arr:PCvArr; idx0:longint; idx1:longint; aval:double); cdecl;
  { dst(idx) = src(idx) ^ value  }
  procedure cvXorS(src:PCvArr; value:CvScalar; dst:PCvArr; mask:PCvArr); cdecl;

  { Draws a rectangle given two opposite corners of the rectangle (pt1 & pt2),
     if thickness<0 (e.g. thickness == CV_FILLED), the filled box is drawn  }

  procedure cvRectangle(img:PCvArr; pt1:CvPoint; pt2:CvPoint; color:CvScalar;
               thickness:longint; line_type:longint; shift:longint); cdecl;
  { Draws ellipse outline, filled ellipse, elliptic arc or filled elliptic sector,
     depending on <thickness>, <start_angle> and <end_angle> parameters. The resultant figure
     is rotated by <angle>. All the angles are in degrees  }

  procedure cvEllipse(img:PCvArr; center:CvPoint; axes:CvSize; angle:double;
                start_angle:double; end_angle:double; color:CvScalar;
                thickness:longint; line_type:longint; shift:longint); cdecl;



  { Implements CAMSHIFT algorithm - determines object position, size and orientation
     from the object histogram back project (extension of meanshift)  }
  function cvCamShift(prob_image:PCvArr; window:CvRect; criteria:CvTermCriteria;
                comp:PCvConnectedComp; box:PCvBox2D):longint; cdecl;

  {***************************************************************************************/
  *                         Working with Video Files and Cameras                           *
  /*************************************************************************************** }
  { "black box" capture structure  }

  type
    CvCapture = record
    end;
    PCvCapture = ^CvCapture;
    P2PCvCapture = ^PCvCapture;

  { start capturing frames from video file  }
  function cvCaptureFromFile(filename:Pchar): PCvCapture; cdecl;


  const
     CV_CAP_ANY = 0;
     CV_CAP_MIL = 100;
     CV_CAP_VFW = 200;
     CV_CAP_V4L = 200;
     CV_CAP_V4L2 = 200;
     CV_CAP_FIREWARE = 300;
     CV_CAP_IEEE1394 = 300;
     CV_CAP_DC1394 = 300;
     CV_CAP_CMU1394 = 300;

  { start capturing frames from camera: index = camera_index + domain_offset (CV_CAP_*)  }
//  function cvCaptureFromCAM(index:longint):PCvCapture; cdecl;

  { grab a frame, return 1 on success, 0 on fail.
    this function is thought to be fast                }
  function cvGrabFrame(capture:PCvCapture):longint; cdecl;

  { get the frame grabbed with cvGrabFrame(..)
   This function may apply some frame processing like
   frame decompression, flipping etc.
  !!!DO NOT RELEASE or MODIFY the retrieved frame!!!  }

  function cvRetrieveFrame(capture:PCvCapture): PIplImage; cdecl;

  { Just a combination of cvGrabFrame and cvRetrieveFrame
     !!!DO NOT RELEASE or MODIFY the retrieved frame!!!       }
  function cvQueryFrame(capture:PCvCapture):PIplImage;  cdecl;

  { stop capturing/reading and free resources  }
  procedure cvReleaseCapture(capture:P2PCvCapture);  cdecl;




{*****************************************************************************}

implementation


 Procedure cvCreateData;                  external cxCore name 'cvCreateData';
 function  cvCreateMatHeader ;            external cxCore name 'cvCreateMatHeader';
 Procedure cvReleaseData;                 external cxCore name 'cvReleaseData';

 function   cvGetSeqElem ;                 external cxCore name 'cvGetSeqElem';
 Function  cvCreateImageHeader;           external cvDLL name 'cvCreateImageHeader';
 Procedure cvReleaseImageHeader;          external cvDLL name 'cvReleaseImageHeader';
 procedure cvReleaseImage(var image: PIplImage); external cxCore;

 procedure  cvCalcOpticalFlowPyrLK;        external cvDLL name 'cvCalcOpticalFlowPyrLK';

 Procedure cvCalibrateCamera;             external cvDLL name 'cvCalibrateCamera';

 Procedure cvFindExtrinsicCameraParams;   external cvDLL name 'cvFindExtrinsicCameraParams';
 Procedure cvRodrigues;                   external cvDLL name 'cvRodrigues';
 Function  cvInvert;                      external cvDLL name 'cvInvert';
 Procedure cvMatMulAdd;                   external cvDLL name 'cvMatMulAdd';
 procedure cvLaplace;                     external cvDLL name 'cvLaplace';
 procedure cvSobel;                       external cvDLL name 'cvSobel';
 function cvHoughLines2;                  external cvDLL name 'cvHoughLines2';
 function cvCreateStructuringElementEx;   external cvDLL name 'cvCreateStructuringElementEx';
 function cvCreateSeq;                    external cvDLL1 name 'cvCreateSeq';
 procedure cvErode;                       external cvDLL1 name 'cvErode';
 procedure cvDilate;                      external cvDLL1 name 'cvDilate';
 procedure cvPyrUp;                       external cvDLL1 name 'cvPyrUp';
 procedure cvPutText;                     external cvDLL1 name 'cvPutText';
 procedure cvInitFont;                    external cvDLL1 name 'cvInitFont';
// function cvContourArea;                  external cvDLL1 name 'cvContourArea';

 procedure cvSmooth;                      external cvDLL name 'cvSmooth';
 procedure cvThreshold;                   external cvDLL name 'cvThreshold';
 procedure cvCanny;                       external cvDLL name 'cvCanny';
 Procedure cvCvtColor;                    external cvDLL name 'cvCvtColor';
 Function  cvCloneImage;                  external cxCore name 'cvCloneImage';

 Function  cvCreateMemStorage;            external cxCore name 'cvCreateMemStorage';
 Procedure cvReleaseMemStorage;           external cxCore name 'cvReleaseMemStorage';
 Procedure cvClearMemStorage;             external cxCore name 'cvClearMemStorage';

 function cvNamedWindow;                  external HighGUI_DLL name 'cvNamedWindow';
 procedure cvShowImage  ;                 external HighGUI_DLL name 'cvShowImage';
 procedure cvDestroyWindow  ;                 external HighGUI_DLL name 'cvDestroyWindow';
 function cvWaitKey;                      external HighGUI_DLL name 'cvWaitKey';
 Procedure cvDrawContours;                external cxCore name 'cvDrawContours';
 function cvFindContours  ;               external cvDLL name 'cvFindContours';
 function cvMinAreaRect2 ;                external cvDLL name 'cvMinAreaRect2';

 procedure cvSnakeImage ;                 external cvDLL name 'cvSnakeImage';
 procedure cvBoxPoints  ;                 external cvDLL name 'cvBoxPoints';

 function  cvHaarDetectObjects;            external cvDLL name 'cvHaarDetectObjects';

 procedure cvSave ;                       external cxCore name 'cvSave';
 function  cvLoad;                         external cxCore name 'cvLoad';

 function cvBoundingRect  ;               external cvDLL name 'cvBoundingRect';
 function cvApproxPoly  ;                 external cvDLL name 'cvFindContours';
 Function  cvFindChessBoardCornerGuesses; external cvDLL name 'cvFindChessBoardCornerGuesses';
 Procedure cvFindCornerSubPix;            external cvDLL name 'cvFindCornerSubPix';

 procedure  cvSetMouseCallback;           external HighGUI_DLL name 'cvSetMouseCallback';
 function   cvCreateTrackbar;             external HighGUI_DLL name 'cvCreateTrackbar';

 procedure cvCircle;                      external cxCore name 'cvCircle';
 procedure cvLine;                        external cxCore name 'cvLine';

 procedure cvWarpAffine;                  external cvDLL name 'cvWarpAffine';
 function  cv2DRotationMatrix;            external cvDLL name 'cv2DRotationMatrix';
 function  cvCreateMat;                   external cxCore name 'cvCreateMat';
 Function  cvLoadImage;                   external HighGUI_DLL name 'cvLoadImage';
 Function  cvSaveImage;                   external HighGUI_DLL name 'cvSaveImage';


 procedure  cvGoodFeaturesToTrack;        external cvDLL name 'cvGoodFeaturesToTrack';


{----------------------------------------------------}

 function cvCreateImage;                  external cxCore name 'cvCreateImage';
 function cvGetSize;                      external cxCore name 'cvGetSize';
 function cvGetSubRect;                   external cxCore name 'cvGetSubRect';
 function cvGetImage;                     external cxCore name 'cvGetImage';
 procedure cvCmpS;                        external cxCore name 'cvCmpS';
 procedure cvCopy;                        external cxCore name 'cvCopy';
 procedure cvInRangeS;                    external cxCore name 'cvInRangeS';
 procedure cvSetZero;                     external cxCore name 'cvSetZero';
 procedure cvZero;                        external cxCore name 'cvSetZero';
 procedure cvSetImageROI;                 external cxCore name 'cvSetImageROI';
 procedure cvResetImageROI;               external cxCore name 'cvResetImageROI';
 procedure cvAddS;                        external cxCore name 'cvAddS';
 procedure cvAddWeighted;                 external cxCore name 'cvAddWeighted';
 procedure cvConvertScale;                external cxCore name 'cvConvertScale';
 procedure cvSplit;                       external cxCore name 'cvSplit';
 procedure cvFlip;                     external cxCore name 'cvFlip';
 procedure cvSubRS ;                       external cxCore name 'cvSubRS';
 procedure cvAnd;                         external cxCore name 'cvAnd';
 procedure cvSub;                         external cxCore name 'cvSub';
 procedure cvSubs;                        external cxCore name 'cvSubs';
 procedure cvXOR;                         external cxCore name 'cvXor';
 function cvGetReal1D;                    external cxCore name 'cvGetReal1D';
 function cvGetReal2D;                    external cxCore name 'cvGetReal2D';
 function cvGetReal3D;                    external cxCore name 'cvGetReal3D';
 function cvGetRealND;                    external cxCore name 'cvGetRealND';

 procedure cvSet1D;                       external cxCore name 'cvSet1D';
 procedure cvSet2D;                       external cxCore name 'cvSet2D';

 procedure cvSetReal1D;                    external cxCore name 'cvSetReal1D';
 procedure cvSetReal2D;                    external cxCore name 'cvSetReal2D';

 procedure cvXorS;                        external cxCore name 'cvXorS';
 procedure cvRectangle;                   external cxCore name 'cvRectangle';
 procedure cvEllipse;                     external cxCore name 'cvEllipse';


 function cvCreateHist;                   external cvDLL name 'cvCreateHist';
 procedure cvCalcArrHist;                 external cvDLL name 'cvCalcArrHist';
 procedure cvGetMinMaxHistValue;          external cvDLL name 'cvGetMinMaxHistValue';
 procedure cvCalcArrBackProject;          external cvDLL name 'cvCalcArrBackProject';
 function cvCamShift;                     external cvDLL name 'cvCamShift';


 function cvCaptureFromFile;              external HighGUI_DLL name 'cvCreateFileCapture';
 function cvGrabFrame;                    external HighGUI_DLL name 'cvGrabFrame';
 function cvRetrieveFrame;                external HighGUI_DLL name 'cvRetrieveFrame';
 function cvQueryFrame;                   external HighGUI_DLL name 'cvQueryFrame';
 procedure cvReleaseCapture;              external HighGUI_DLL name 'cvReleaseCapture';

 {----------------------------------------------------}
 Procedure cvMatMul( A,B,D : PCvArr );
 begin
    cvMatMulAdd(A,B,nil,D);
 end;


 function CV_MAT_TYPE( flags : integer): integer;
 begin
    Result:=(flags and CV_MAT_TYPE_MASK);
 end;

 function CV_MAT_DEPTH( flags : integer): integer;
 begin
    Result:=(flags and CV_MAT_DEPTH_MASK);
 end;

 function CV_MAT_CN( flags : integer): integer;
 begin
    Result:=((flags and CV_MAT_CN_MASK) shr 3)+1;
 end;

 function CV_ELEM_SIZE( type_ : integer): integer;
 begin
    Result:=(CV_MAT_CN(type_) shl (($e90 shr CV_MAT_DEPTH(type_)*2) and 3));
 end;

 function cvMat_( rows : Integer; cols : Integer; type_: Integer; data : Pointer) : CvMat ;
 begin
    type_:= CV_MAT_TYPE(type_);
    Result.type_:= CV_MAT_MAGIC_VAL or CV_MAT_CONT_FLAG or type_;
    Result.cols := cols;
    Result.rows := rows;
    Result.step := Result.cols*CV_ELEM_SIZE(type_);
    Result.ptr := PUCHAR(data);
    Result.refcount := nil;
 end;


 Function cvmGet( const mat : PCvMat; i, j : integer): Single;
 var
  type_ : integer;
  ptr   : PUCHAR;
  pf    : PSingle;
 begin
    type_:= CV_MAT_TYPE(mat.type_);
    assert(  ( i<mat.rows) and (j<mat.cols) );

    if type_ = CV_32FC1 then begin
       ptr:=mat.ptr;
       inc(ptr, mat.step*i+ sizeOf(Single)*j);
       pf:=PSingle(ptr);
       Result:=pf^;
    end;

 end;


 Procedure cvmSet( mat : PCvMat; i, j : integer; val: Single  );
 var
  type_ : integer;
  ptr   : PUCHAR;
  pf    : PSingle;
 begin
    type_:= CV_MAT_TYPE(mat.type_);
    assert(  ( i<mat.rows) and (j<mat^.cols) );

    if type_ = CV_32FC1 then begin
       ptr:=mat.ptr;
       inc(ptr, mat.step*i+ sizeOf(Single)*j);
       pf:=PSingle(ptr);
       pf^:=val;
    end;

 end;

 Function cvPseudoInverse( const src : PCvArr; dst : PCvArr ) : double;
 begin
    cvInvert( src, dst, CV_SVD );
 end;


 Function cvSize_( width, height : integer ) : TcvSize;
 begin
    Result.width:=width;
    Result.height:=height;
 end;
{
 Function cvFont_( font_face : integer;ascii,greek ,cyrillic:pInteger;
  hscale, vscale , shear: float; thickness : integer; dx : float; line_type : integer) : TCvFont;
 begin
    Result.font_face:=   font_face;
    Result.ascii    :=   ascii ;
    Result.greek    :=   greek;
    Result.cyrillic :=   cyrillic;
    Result.hscale   :=   hscale;
    Result.vscale   :=   vscale;
    Result.shear    :=   shear;
    Result.thickness:=   thickness;
    Result.dx       :=   dx;
    Result.line_type:=   line_type;
 end;
 }
{-----------------------------------}
procedure cvCalcHist(image:P2PIplImage; hist:PCvHistogram; accumulate:longint; mask:PCvArr);
begin
//      cvCalcArrHist( (CvArr**)image, hist, accumulate, mask );
      cvCalcArrHist(p2pCvArr(image), hist, accumulate, mask );

end;

procedure cvCalcBackProject(image:P2PIplImage; dst:PCvArr; hist:PCvHistogram);
begin
  cvCalcArrBackProject(P2PCvArr(image), dst, hist);
end;


function cvScalar_(val0:double; val1:double; val2:double; val3:double):CvScalar;
var
      scalar: CvScalar ;
begin
      scalar.val[0] := val0; scalar.val[1] := val1;
      scalar.val[2] := val2; scalar.val[3] := val3;
      result := scalar;
end;

function cvScalarAll_(val0123:double):CvScalar;
var
        scalar: CvScalar;
begin
      scalar.val[0] := val0123;
      scalar.val[1] := val0123;
      scalar.val[2] := val0123;
      scalar.val[3] := val0123;
      result := scalar;
end;



function cvRound(value:double):longint;
var
        temp: double;

begin
      {*
       the algorithm was taken from Agner Fog's optimization guide
       at http://www.agner.org/assem
       *}
    //  temp := value + 6755399441055744.0;
    //  result := (int)*((uint64*)&temp);
      result := round(value);

end;

function cvFloor(value:double):longint;
begin
        result := floor(value);
end;

function cvPoint2D32f_(  x, y: single ): cvPoint2D32f;
begin
    result.x := x;
    result.y := y;
end;

function cvPoint_( x, y: longint ): CvPoint;
var
    p: CvPoint;
begin
    p.x := x;
    p.y := y;

    result := p;
end;
{
function cvSlice_( x, y: integer ): integer;
var
    p: CvPoint;
begin
    p.x := x;
    p.y := y;

    result := p;
end;
}
function  cvTermCriteria_( type_: longint; max_iter: longint; epsilon: double ): CvTermCriteria;
var
    t: CvTermCriteria;
begin
    t.type_ := type_;
    t.maxIter := max_iter;
    t.epsilon := epsilon;

    result := t;
end;

function CV_RGB(r,g,b : longint) : CvScalar;
begin
   CV_RGB := cvScalar_(b,g,r,0);
end;

procedure CV_SWAP(var a, b, t: pointer);
begin
        t := a;
        a := b;
        b := t;
end;


function  cvPointFrom32f_( point: CvPoint2D32f ): CvPoint;
var
    ipt: CvPoint;
begin
    ipt.x := cvRound(point.x);
    ipt.y := cvRound(point.y);

    result := ipt;
end;


procedure cvEllipseBox(img:PCvArr; box:CvBox2D; color:CvScalar; thickness:longint;
              line_type:longint; shift:longint);
var
      axes: CvSize;
begin
      axes.width := cvRound(box.size.height *0.5);
      axes.height := cvRound(box.size.width *0.5);

      cvEllipse( img, cvPointFrom32f_( box.center ), axes, (box.angle*180/pi),
                 0, 360, color, thickness, line_type, shift );
end;

function  cvRect_( x, y, width, height: longint ): CvRect;
var
    r: CvRect;
begin
    r.x := x;
    r.y := y;
    r.width := width;
    r.height := height;

    result := r;
end;


function  cvPointTo32f_(point: CvPoint ):  CvPoint2D32f;
var
    ipt: CvPoint2D32f;
begin
    ipt.x := point.x;
    ipt.y := point.y;
    result := ipt;
end;


function hsv2rgb(  hue : float )  :CvScalar ;
var rgb : array [0..2] of integer;
    p,sector  :integer;
    const sector_data : array [0..5,0..2] of integer=
        ((0,2,1), (1,2,0), (1,0,2), (2,0,1), (2,1,0), (0,1,2));

begin
    hue :=hue *  0.033333333333333333333333333333333;
    sector := cvFloor(hue);
    p := cvRound(255*(hue - sector));
    if (sector and 1) = 1 then p := 255
    else p := 0;

    rgb[sector_data[sector][0]] := 255;
    rgb[sector_data[sector][1]] := 0;
    rgb[sector_data[sector][2]] := p;

    result :=  cvScalar_(rgb[2], rgb[1], rgb[0],0);
end;

 function CV_IS_HAAR_CLASSIFIER(haar : pointer) : boolean;
 begin
    result := false;
    result :=  (haar <>nil) and
       ( ( pCvHaarClassifierCascade(haar).flags and CV_MAGIC_MASK ) = CV_HAAR_MAGIC_VAL  ) ;
 end;
{-----------------------------------------------------------------------------
  Procedure:  IplImage2Bitmap
  Author:     De Sanctis
  Date:       23-set-2005
  Arguments:  iplImg: PIplImage; bitmap: TBitmap
  Description: convert a IplImage to a Windows bitmap
-----------------------------------------------------------------------------}
procedure IplImage2Bitmap(iplImg: PIplImage; var bitmap: TBitmap);
  VAR
    i        :  INTEGER;
    j        :  INTEGER;
    offset   :  longint;
    dataByte :  PByteArray;
    RowIn    :  pByteArray;
    channelsCount : integer;
BEGIN
  TRY


   // assert((iplImg.Depth = 8) and (iplImg.NChannels = 3),
    //            'IplImage2Bitmap: Not a 24 bit color iplImage!');

    bitmap.Height := iplImg.Height;
    bitmap.Width := iplImg.Width;
    FOR j := 0 TO Bitmap.Height-1 DO
    BEGIN
      // origin BL = Bottom-Left
      if (iplimg.Origin = IPL_ORIGIN_BL) then
              RowIn  := Bitmap.Scanline[bitmap.height -1 -j ]
      else
              RowIn  := Bitmap.Scanline[j ];

      offset := longint(iplimg.ImageData) + iplImg.WidthStep * j;
      dataByte := pbytearray( offset);

      if (iplImg.ChannelSeq = 'BGR') then
      begin
        {direct copy of the iplImage row bytes to bitmap row}
        CopyMemory(rowin, dataByte, iplImg.WidthStep);
      end
      else
      if  (iplImg.ChannelSeq =  'GRAY') then
          FOR i := 0 TO Bitmap.Width-1 DO
          begin
                RowIn[3*i] := databyte[i];
                RowIn[3*i+1] := databyte[i];
                RowIn[3*i+2] := databyte[i];
          end
      else
          FOR i := 0 TO 3*Bitmap.Width-1 DO
            begin
                RowIn[i] := databyte[i+2] ;
                RowIn[i+1] := databyte[i+1] ;
                RowIn[i+2] := databyte[i];
            end;
    END;

  Except

  END
END; {IplImage2Bitmap}

{****************************************************************************}
end.
